package com.woniu.platform.service.impl;

import com.woniu.platform.entity.PlatformMenu;
import com.woniu.platform.mapper.PlatformMenuMapper;
import com.woniu.platform.service.PlatformMenuService;
import com.woniu.util.utils.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PlatformMenuServiceImpl implements PlatformMenuService {

    @Autowired
    private PlatformMenuMapper platformMenuMapper;


    /**
     * 封装成父子菜单的形式的方法
     * @param platformMenusList
     * @return
     */
    private List<PlatformMenu> getMenus(List<PlatformMenu> platformMenusList) {
        List<PlatformMenu> parentMenus = platformMenusList.stream().filter(e ->e.getFatherId() ==null)
                .collect(Collectors.toList());
        for (PlatformMenu parentMenu: parentMenus) {
            List<PlatformMenu> childrenList = new ArrayList<PlatformMenu>();
            for(PlatformMenu menu:platformMenusList){
                //找出一级菜单对应的二级菜单
                if(parentMenu.getId().equals(menu.getFatherId())){
                    childrenList.add(menu);
                }
            }
            parentMenu.setChildrenMenu(childrenList);
        }
        return parentMenus;
    }

    /**
     * 通过用户账号请求菜单列表
     * @param account
     * @return
     */
    @Override
    public HttpResult<?> queryPlatformMenuByAccount(String account) {

        List<PlatformMenu> allMenus = platformMenuMapper.queryPlatformMenusByAccount(account);
        List<PlatformMenu> theEndMenus = getMenus(allMenus);
        return new HttpResult<>().ok(theEndMenus);
    }

    /**
     * 查询所有菜单
     * @return
     */
    @Override
    public HttpResult queryallMenu() {
       List<PlatformMenu> menuList = platformMenuMapper.selectList(null);
       List<PlatformMenu> finallList = getMenus(menuList);
        return new HttpResult<>().ok(finallList);
    }
}
